package com.shuo.limit.aspect.util;

import com.shuo.limit.enums.LimitType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by shuoGG on 2018/10/9
 */
@Component
public class RateKeyGenerator {

    @Value("${spring.application.name:app}")
    private String appName;

    public String getKey(LimitType type, JoinPoint joinPoint) {
        StringBuilder key = new StringBuilder();
        HttpServletRequest request = getRequest();
        key.append("rateLimit:").append(appName).append(":");
        switch (type) {
            case ALL:
                key.append(getMethodSign(joinPoint));
                break;
            case IP:
                key.append(getMethodSign(joinPoint)).append(getRemoteIp(request));
                break;
            default:
        }
        return key.toString();
    }

    private String getMethodSign(JoinPoint joinPoint) {
        StringBuilder key = new StringBuilder();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        key.append(joinPoint.getTarget().getClass().getName());
        key.append(":");
        key.append(signature.getMethod().getName());
        key.append(":");
        Class[] parameterTypes = signature.getParameterTypes();
        for (Class clazz : parameterTypes) {
            key.append(clazz.getName());
        }
        return key.toString();
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    private String getRemoteIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

}
